package com.sxs.app.controller;


import com.github.pagehelper.PageInfo;
import com.sxs.app.entity.AppInfo;
import com.sxs.app.entity.DevUser;
import com.sxs.app.intercept.SeesionUtil;
import com.sxs.app.service.AppinfoService;
import com.sxs.app.vo.ResultVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/appinfo")
public class AppinfoController {

    @Autowired
    AppinfoService appinfoService;

    //分页带条件查询
    @PostMapping("/page")
    public ResultVo page(@RequestBody(required = false) AppInfo appInfo, HttpServletRequest request,
                         @RequestParam(defaultValue = "1") Integer pageNum){
        String token = request.getHeader("token");
        String[] split = token.split("-");
        String account = split[1];
        String typeStr = split[3];
        if(typeStr.equals("1")){
            appInfo.setStatus(1L);
        }else if(typeStr.equals("2")){
            Long devId = appinfoService.getDevId(account);
            appInfo.setDevid(devId);
        }
        PageInfo<AppInfo> page = appinfoService.page(appInfo,pageNum);
        return ResultVo.success("",page);
    }

    @Value("${web.upload-path}")
    private String uploadPath;
    //新增、修改appinfo
    @PostMapping("/saveOrUpdate")
    public ResultVo save(AppInfo appInfo, MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("token");

        if(file!=null && !file.isEmpty()){
            //前端有文件传来
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if(file.getSize()>1024*500*1024){
                return ResultVo.error("文件超过500K");
            }else if(extension.equalsIgnoreCase("jpg")
                    || extension.equalsIgnoreCase("jpeg")
                    || extension.equalsIgnoreCase("png")
                    || extension.equalsIgnoreCase("gif")
            ){
                //正常上传
                File savePath = new File(uploadPath+"upload");
                if(!savePath.exists()){
                    savePath.mkdirs();
                }
                //防止重名覆盖
                String fileName = UUID.randomUUID().toString().replace("-", "");
                File saveFile = new File(uploadPath+"upload/"+fileName+"."+extension);
                try {
                    file.transferTo(saveFile);
                    appInfo.setLogopicpath("/upload/"+fileName+"."+extension);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.error("文件出现异常");
                }
            }else {
                return ResultVo.error("文件格式不对");
            }
        }

        DevUser devUser = (DevUser) SeesionUtil.get(token);
        //操作数据库方面的代码
        if(appInfo.getId()==null){
            appInfo.setCreatedby(devUser.getId());  //创建者
            appInfo.setDevid(devUser.getId());  //开发者
            appInfo.setCreationdate(new Date());    //当前时间点
            appInfo.setStatus(1L);
            appInfo.setDownloads(0L);   //下载量
            appInfo.setId(devUser.getId());
            appinfoService.save(appInfo);
        }else {
            appInfo.setModifyby(devUser.getId());   //更新者
            appInfo.setModifydate(new Date()); //最新更新时间
            appInfo.setStatus(1L);
            appinfoService.update(appInfo);
        }
        return ResultVo.success("",null);
    }

    //删除
    @DeleteMapping("/{id}")
    public ResultVo del(@PathVariable Long id){
        appinfoService.del(id);
        return ResultVo.success("",null);

    }

    //这个是通过appid查找信息（得到新增版本上面的app信息）
    @GetMapping("/{id}")
    public ResultVo getId(@PathVariable Long id){
        AppInfo appInfo = appinfoService.getBy(id);
        return ResultVo.success("",appInfo);
    }

    //上架、下架
    @PutMapping("/{appid}")
    public ResultVo upOrOff(@PathVariable Long appid){
        AppInfo appInfo =appinfoService.getBy(appid);
        if(appInfo.getStatus() == 4L){
            appInfo.setStatus(5L);
        }else if (appInfo.getStatus() == 5L){
            appInfo.setStatus(4L);
        }else if(appInfo.getStatus() == 2L){
            appInfo.setStatus(4L);
        }
        appinfoService.update(appInfo);
        return ResultVo.success("",null);
    }

    //apkname校验唯一性
    @PostMapping("/validate")
    public ResultVo validate(@RequestBody AppInfo appInfo){
        Boolean flag = appinfoService.validate(appInfo);
        if(flag == true){
            return ResultVo.success("",null);
        }else {
            return ResultVo.error("");
        }
    }

    //审核
    @GetMapping("/shenhe")
    public ResultVo audit(long appid,Integer ofType){
        try {
            appinfoService.shenhe(appid,ofType);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("");
        }
        return ResultVo.success("",null);
    }
}
